package com.morningstar.system.satoken;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import com.morningstar.system.feign.interceptor.FeignInterceptor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;
import java.util.Objects;

/**
 * @author yanglianshan
 */
@Slf4j
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Resource
    private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("addInterceptors SaInterceptor");
        registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
                .addPathPatterns("/**")
                .excludePathPatterns("/feign/**");

        registry.addInterceptor(new FeignInterceptor())
                .addPathPatterns("/feign/**");
    }

    /**
     * web mvc 默认会注册一个Converter 导致重写的MappingJackson2HttpMessageConverter 会失效
     *
     * @param converters the list of configured converters to be extended
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        boolean result = converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter);
        log.info("extendMessageConverters result:{}", result);
        if (Objects.isNull(mappingJackson2HttpMessageConverter)) {
            converters.add(0, new MappingJackson2HttpMessageConverter());
        } else {
            log.info("extendMessageConverters mappingJackson2HttpMessageConverter:{}", mappingJackson2HttpMessageConverter);
            converters.add(0, mappingJackson2HttpMessageConverter);
        }
    }
}
